package com.qingfeng.framework.resolver;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * 公共模块
 * spring mvc异常处理类(跳转到异常页面、处理json格式异常信息)
 * @author linxz 
 * @date 2014年12月22日 下午1:50:58 
 * @Description:
 */
public class ExceptionResolver extends SimpleMappingExceptionResolver {

	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		String viewName = determineViewName(ex, request);// 获取异常处理结果名称

		if (viewName == null) {// 为空，服务器内部异常
			return null;
		}
		
		String accept = request.getHeader("accept");
		String xRequest = request.getHeader("X-Requested-With");
		boolean result = (xRequest != null && xRequest.indexOf("XMLHttpRequest") > -1);

		if (accept.indexOf("application/json") > -1 || result) {// JSON格式返回
			try {
				response.setContentType("text/xml; charset=UTF-8");
				PrintWriter writer = response.getWriter();
				writer.write(ex.getMessage());
				writer.flush();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return null;
		} else {// JSP格式返回
			Integer statusCode = determineStatusCode(request, viewName);

			if (statusCode != null) {
				applyStatusCodeIfPossible(request, response, statusCode);
			}
			
			return getModelAndView(viewName, ex, request);
		}
		
	}
}
